package grpc

import (
	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/pkg/log"
	"gitee.com/zawei/yggdrasil/pkg/transport/server"
	"google.golang.org/grpc"
)

var grpcSvr *grpcServer

func init() {
	grpcSvr = getConfig().Build()
	server.RegisterServer(grpcSvr)
}

func getConfig() *Config {
	c := new(Config)
	if err := config.Get("server.grpc").Scan(c); err != nil {
		log.Fatalw("fault to scan grpc config", "error", err)
	}
	return c
}

func WithServerOption(opts ...grpc.ServerOption) {
	grpcSvr.cfg.WithServerOption(opts...)
}

func WithStreamInterceptor(interceptors ...grpc.StreamServerInterceptor) error {
	grpcSvr.cfg.WithStreamInterceptor(interceptors...)
	return nil
}

func WithUnaryInterceptor(interceptors ...grpc.UnaryServerInterceptor) error {
	grpcSvr.cfg.WithUnaryInterceptor(interceptors...)
	return nil
}

func RegisterService(desc *grpc.ServiceDesc, svr interface{}) {
	grpcSvr.cfg.serviceDesc = append(grpcSvr.cfg.serviceDesc, struct {
		svr  interface{}
		desc *grpc.ServiceDesc
	}{svr: svr, desc: desc})
}
